package com.test.concurrent;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;

/**
 * todo 忘了要去测试
 */
public class MyContainer {
    /*volatile*/ List list = new ArrayList();

    public void add(Object o) {
        list.add(o);
    }

    public int size() {
        return list.size();
    }


    public static void main(String[] arg) {
        MyContainer myContainer = new MyContainer();
        //门闩
        CountDownLatch countDownLatch = new CountDownLatch(1);
        new Thread(() -> {
            System.out.println("t2 start");
            if (myContainer.size() != 5) {
                try {
                    //释放
                    countDownLatch.await();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
            System.out.println("t2 end");
        }, "t2").start();


        /*try {
            TimeUnit.SECONDS.sleep(1);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }*/
        new Thread(() -> {
            System.out.println("t1 start");
            for (int i = 0; i < 10; i++) {
                myContainer.add(new Object());
                System.out.println(i);
                if (myContainer.size() == 5) {
                    countDownLatch.countDown();
                }
                //不睡会执行过快
                try {
                    TimeUnit.SECONDS.sleep(1);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }, "t1").start();
    }
}
